package com.ocom.webapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.CompanyServiceUrl;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.dto.*;
import com.ocom.common.entity.company.*;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.GetComRequestRequest;
import com.ocom.common.request.company.GetDockApiUrlRequest;
import com.ocom.common.request.company.GetSeverReplyApiParaRequest;
import com.ocom.common.request.web.DockPageApiRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.response.GetComRequestResponse;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.RSAUtils;
import com.ocom.common.utils.RandomUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.company.ComLoginAuthCodeRequest;
import com.ocom.common.vo.company.DockApiUrlVo;
import com.ocom.common.vo.company.SrvCodeVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.CompanyClientService;
import com.ocom.webapi.feign.ExposeapiFeignService;
import com.ocom.webapi.feign.PayConfigClientService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
@Slf4j
@RestController
public class DockController {

    @Autowired
    PayConfigClientService payConfigClientService;

    @Autowired
    CompanyClientService companyClientService;

    @Autowired
    ExposeapiFeignService exposeapiFeignService;

    @Resource
    RedisUtil redisUtil;

    /**
     *@Description:获取平台列表（Dock/dockList）
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2023/3/17 14:38       
     */
    @PostMapping(WebApiServiceUrl.Url_DockDockList)
    public Result dockDockList(@RequestBody JSONObject jsonObject){
        return payConfigClientService.getDockList(jsonObject.getString("dockCode"),jsonObject.getString("dockName"),
                jsonObject.getInteger("page"),jsonObject.getInteger("size"));
    }

    /**
     *@Description:添加平台
     * @author lu 
     * @param jsonObject 
     * @return com.ocom.common.resp.Result
     * @date 2023/3/17 16:15       
     */
    @PostMapping(WebApiServiceUrl.Url_DockAddDock)
    public Result dockAddDock(@RequestBody JSONObject jsonObject){
        return payConfigClientService.addDock(jsonObject.getString("dockCode"),jsonObject.getString("dockName"),
                jsonObject.getInteger("serverMode"),jsonObject.getInteger("signMode"),jsonObject.getString("remark"));
    }

    /**
     *@Description:修改平台
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2023/3/20 13:38       
     */
    @PostMapping(WebApiServiceUrl.Url_DockModifyDock)
    public Result dockModifyDock(@RequestBody JSONObject jsonObject){
        return payConfigClientService.updateDock(jsonObject.getString("dockCode"),jsonObject.getString("dockName"),
                jsonObject.getInteger("serverMode"),jsonObject.getInteger("signMode"),jsonObject.getString("remark"));
    }

    /*
    * @Description:平台协议DockApi
     * @author
     * @param
     * @return com.ocom.common.resp.Result
     * @date 2023/5/12 16:00
     *  */

    @PostMapping(WebApiServiceUrl.Url_dockPageOnshow)
    public Result dockPageOnshow(){
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        return companyClientService.getComDockPageList(yoCiUser.getComId());
    }

    @PostMapping(WebApiServiceUrl.Url_DockDockApiList)
    public Result dockApiList(@Validated  @RequestBody DockApiListDto request){
        return companyClientService.getDockApiList(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockAddDockApi)
    public Result addDockApi(@RequestBody EntityDockApi request){
        return companyClientService.addDockApi(request);
    }

    @PostMapping(WebApiServiceUrl.Url_dockPageApi)
    public Result dockPageApi(@RequestBody DockPageApiRequest request) throws Exception {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();

        GetDockApiUrlRequest getDockApiUrlRequest=new GetDockApiUrlRequest();
        getDockApiUrlRequest.setDockCode(request.getDockCode());
        getDockApiUrlRequest.setComId(yoCiUser.getComId());
        getDockApiUrlRequest.setGrade(0);
        if(!CommonUtil.isNull(request.getServerCode())){
            getDockApiUrlRequest.setGrade(10);
        }
        getDockApiUrlRequest.setServerCode(request.getServerCode());
        Result result =   companyClientService.getDockApiUrl(getDockApiUrlRequest);

        log.info("执行平台链接 【{}】【{}】",getDockApiUrlRequest,result);

        if(result.getCode()!=200){
            return result;
        }
        List<DockApiUrlVo> list = JSON.parseArray(JSON.toJSONString(result.getData()),DockApiUrlVo.class);
        DockApiUrlVo dockApiUrlVo =null;
        for (DockApiUrlVo dockApiUrlVo1:list){
            if(dockApiUrlVo1.getDockApiCode().equals(request.getDockApiCode())){
                dockApiUrlVo = dockApiUrlVo1;
                break;
            }
        }
        if(dockApiUrlVo==null){
            return ResultUtil.error(ResultEnum.Err_4078);
        }

        Object code2 = "";
        if(request.getDockCode().equals("dingcan")) {
            GetSeverReplyApiParaRequest replyApiParaRequest = new GetSeverReplyApiParaRequest();
            replyApiParaRequest.setDockCode(request.getDockCode());
            replyApiParaRequest.setDockApiCode(request.getDockApiCode());
            replyApiParaRequest.setSvrAppid("srvappiddingcan");
            replyApiParaRequest.setKeyType(2);
            Result result1 = companyClientService.getSeverReplyApiPara(replyApiParaRequest);
            SrvCodeVo srvCodeVo = JSON.parseObject(JSON.toJSONString(result1.getData()), SrvCodeVo.class);

            UserInfo userInfo = new UserInfo();
            userInfo.setComId(yoCiUser.getComId());
            userInfo.setUserId(yoCiUser.getId());
            userInfo.setUserName(yoCiUser.getUsername());
            userInfo.setTimestamp(System.currentTimeMillis());
            userInfo.setRandom(RandomUtil.getRandomString(10));
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) RSAUtils.getPrivateKey(srvCodeVo.getKey());

            code2 = RSAUtils.encryptByPrivate(JSON.toJSONBytes(userInfo), rsaPrivateKey);

        } else if(request.getDockCode().equals("ocomkq")){
            GetComRequestRequest getComRequestRequest=new GetComRequestRequest();
            getComRequestRequest.setComId(request.getComId());
            getComRequestRequest.setDockCode("ocomkq");
            getComRequestRequest.setDockApiCode("ocomkq#login");
            Result result1=companyClientService.getComRequest(getComRequestRequest);
         //   System.out.println(result1);
            if (200 == result1.getCode() && null != result1.getData()) {
                GetComRequestResponse getComRequestResponse = JSON.parseObject(JSON.toJSONString(result1.getData()), GetComRequestResponse.class);

                JSONObject jsonObject  = JSON.parseObject(getComRequestResponse.getRsaPri());
                jsonObject.put("comId",request.getComId());
                Result result2 = exposeapiFeignService.authLogin(jsonObject);
                if(result2.getCode()==200){
                    code2=(String) result2.getData();
                }
            }
        }else{
            ComLoginAuthCodeRequest comLoginAuthCodeRequest =new ComLoginAuthCodeRequest();
            comLoginAuthCodeRequest.setServerCode(request.getServerCode());
            comLoginAuthCodeRequest.setComAppid(request.getComAppid());
            comLoginAuthCodeRequest.setUserId(yoCiUser.getId());
            comLoginAuthCodeRequest.setUserName(yoCiUser.getUsername());
            Result result1  = companyClientService.getComLoginAuthCode(comLoginAuthCodeRequest);
            code2 = result1.getData();

            log.info("执行平台链接2 【{}】【{}】",comLoginAuthCodeRequest,result1);
        }


        Map<String,Object>  objectMap =new HashMap<>();
        objectMap.put("opCode",1);
        objectMap.put("url",dockApiUrlVo.getRequestUrl()+"?code="+code2);
        return ResultUtil.success(objectMap);
    }

    @PostMapping(WebApiServiceUrl.Url_DockModifyDockApi)
    public Result modifyDockApi(@RequestBody EntityDockApi request){
        return companyClientService.updateDockApi(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockSetDockApiUrl)
    public Result setDockApiUrl(@RequestBody DockUrlSetDto request){
        return companyClientService.setDockApiUrl(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockDockServerList)
    public Result dockServerList(@RequestBody DockServerListDto request){
        return companyClientService.getDockServerList(request);
    }


    @PostMapping(WebApiServiceUrl.Url_DockAddDockServer)
    public Result addDockServer(@RequestBody EntityDockServer request){
        return companyClientService.addDockServer(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockModifyDockServer)
    public Result modifyDockServer(@RequestBody EntityDockServer request){
        return companyClientService.updateDockServer(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockComDockList)
    public Result comDockList(@RequestBody CompanyDockListDto request){
        return companyClientService.getComDockList(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockAddComDock)
    public Result addComDock(@RequestBody EntityCompanyDock request){
        return companyClientService.addComDock(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockModifyComDock)
    public Result modifyComDock(@RequestBody EntityCompanyDock request){
        return companyClientService.updateComDock(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockDeleteComDock)
    public Result deleteComDock(@RequestBody EntityCompanyDock request){
        return companyClientService.removeComDock(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockGetDockKey)
    public Result getDockKey(@RequestBody DockKeyDto request){
        return companyClientService.getDockKey(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockSaveDockKey)
    public Result saveDockKey(@RequestBody EntityDockKey request){
        return companyClientService.saveDockKey(request);
    }
    @Data
    public static class  UserInfo{
        Long comId;
        Long userId;
        String userName;
        //时间戳
        Long timestamp;
        //随机字符串
        String random;
    }

    /**
     * 6.23生成单位登录验证码（getComLoginAuthCode）
     */
    @PostMapping(CompanyServiceUrl.URL_getComLoginAuthCode)
    public Result getComLoginAuthCode(@RequestBody ComLoginAuthCodeRequest request) {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();

        request.setUserId(yoCiUser.getId());
        request.setUserName(yoCiUser.getUsername());

        String code = "XAK"+request.getComAppid()+ RandomUtil.getRandomString(20);
        redisUtil.set("SsoCode:"+request.getServerCode()+":"+code,request,31536000l);
        return ResultUtil.success(code);
    }

    @PostMapping(WebApiServiceUrl.Url_DockGetDockApiUrl)
    public Result getDockApiUrl(@RequestBody GetDockApiUrlRequest request){
        return companyClientService.getDockApiUrl(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockComDockApiConfig)
    public Result comDockApiConfig(@RequestBody GetDockApiConfigDto request){
        return companyClientService.getDockApiConfig(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockSaveDockApiConfig)
    public Result saveDockApiConfig(@RequestBody EntityComDockApi request){
        return companyClientService.saveDockApiConfig(request);
    }

    @PostMapping(WebApiServiceUrl.Url_DockNewMd5Key)
    public Result newMd5Key(@RequestBody Object request){
        return null;
    }

    @PostMapping(WebApiServiceUrl.Url_DockNewRsa)
    public Result newRsa(@RequestBody Object request){
        return null;
    }

    @PostMapping(WebApiServiceUrl.Url_DockDockComList)
    public Result dockComList(@RequestBody CompanyDockComListDto request){
        return companyClientService.getDockComList(request);
    }

    @PostMapping(WebApiServiceUrl.Url_decodeFile)
    public Result decodeFile(String pwd, @RequestPart("file") MultipartFile file){
        try {

            // PFX文件密码
            char[] pfxPassword = pwd.toCharArray();

            // 初始化KeyStore
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            keystore.load(file.getInputStream(), pfxPassword);

            // 获取别名
//            String alias = "your_alias"; // 替换为PFX文件中的别名
            String alias = keystore.aliases().nextElement();
            System.out.println("alias：" + alias);


            // 获取私钥
            PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, pfxPassword);
            // 获取证书
            Certificate cert = keystore.getCertificate(alias);
            // 获取公钥
            PublicKey publicKey = cert.getPublicKey();

            // 输出密钥信息
            System.out.println("PrivateKey: " + convertPrivateKeyToString(privateKey));
            System.out.println("PublicKey: " + convertPublicKeyToString(publicKey));


            Map<String,String> stringMap = new HashMap<>();

            stringMap.put("单位私钥privateKey",convertPrivateKeyToString(privateKey));
            stringMap.put("单位公钥publicKey",convertPublicKeyToString(publicKey));

            stringMap.put("银行公钥publicKey","MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD//4G/uB5mqZ7oEItuhHME0iWi3JDSqdpmPFHCMczXhK+OaJArX6UniUnZFAU4iRqSvvMO+xyqzsfJKE/cuc8r1z2ewjKkzRg62n8t2qbGqY5wGgHpnjdYmnnQkxoLTDVQES6Zf7C09prgmygT31IQRBsnb1P5cUEuy9K1PwONEQIDAQAB");



            return ResultUtil.success(stringMap);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    // 将私钥转换为字符串
    private static String convertPrivateKeyToString(PrivateKey privateKey) {
        byte[] privateKeyBytes = privateKey.getEncoded();
        return Base64.getEncoder().encodeToString(privateKeyBytes);
    }
    private static String convertPublicKeyToString(PublicKey privateKey) {
        byte[] privateKeyBytes = privateKey.getEncoded();
        return Base64.getEncoder().encodeToString(privateKeyBytes);
    }
}
